package edu.johnpank.libassistant.controllers

import edu.johnpank.libassistant.entity.User
import edu.johnpank.libassistant.enums.Role
import edu.johnpank.libassistant.services.UserService
import edu.johnpank.libassistant.util.UserValidator
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.ComponentScan
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.PostMapping
import java.time.LocalDateTime
import java.time.ZoneOffset
import javax.validation.Valid

@Controller
@ComponentScan
class  LoginController(
    @Autowired
    private val userValidator: UserValidator,
    private val userService: UserService,
    private val passwordEncoder: PasswordEncoder
){
    @GetMapping("auth/login")
    fun showLoginPage(model: Model): String {

        return "auth/login_page"
    }

    @GetMapping("auth/registration")
    fun showRegistrationPage(@ModelAttribute("newUser") newUser: User): String{
        return "auth/reg_page"
    }

    @PostMapping("auth/registration")
    fun regNewUser(@ModelAttribute("newUser") @Valid user: User,
                   bindingResult: BindingResult,
                   model: Model
    ): String{
//        println(user)

        user.password = passwordEncoder.encode(user.password)

        userValidator.validate(user, bindingResult)

        if (bindingResult.hasErrors())
            return "auth/reg_page"

        user.roles.add(Role.ROLE_READER)

        if (user.regDate == 0L){
            user.regDate = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) * 1000
        }

        userService.addUser(user)

        return "redirect:/auth/login"
    }
}